package com.sunday.authorization.security.authentication;

import com.sunday.common.core.enums.ErrorCodeEnum;
import com.sunday.common.core.remoting.rest.response.RestResponse;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 异常处理
 * @see ExceptionTranslationFilter#handleSpringSecurityException(HttpServletRequest, HttpServletResponse, FilterChain, RuntimeException) 异常分解处理
 * @see Http403ForbiddenEntryPoint#commence(HttpServletRequest, HttpServletResponse, AuthenticationException)
 * @see Http403ForbiddenEntryPoint 参考
 * @author sunday
 * @since 2024/3/21
 */
@Slf4j
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("登陆失败 url : {} , error : {}", request.getRequestURI(), authException.toString());
        // A0301 访问未授权
        RestResponse restResponse = RestResponse.error(ErrorCodeEnum.A0_301, RestResponse.ShowTypeEnum.ERROR_MESSAGE);
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getOutputStream().write(restResponse.toJson().getBytes(StandardCharsets.UTF_8));
    }

}
